import { Tools } from "../../common/Tools";
import { AudioManager1 } from "../../manager/AudioManager1";
import { EventManager } from "../../manager/EventManager";
import TouchScale from "../../item/Common/TouchScale";
import LevelBase from "../../LevelBase";
import LvItem from "../../LvItem";
import LvItem_15 from "./LvItem_15";
import { BUNDLE_TYPE_ENUM, EVENT_NAME_ENUM } from "../../base/EnumIndex";
import { TOUCH_MOVE_LEN } from "../../base/GameIndex";
import { UIManager } from "../../manager/UIManager";

const { ccclass, property } = cc._decorator;

/** 关卡15 */
@ccclass
export default class LevelPre_15 extends LevelBase {
    @property({ type: cc.Node, displayName: "viewBg节点" })
    viewBg: cc.Node = null;
    @property({ type: cc.Label, displayName: "二级标题" })
    sTitleLab: cc.Label = null;
    @property({ type: cc.Node, displayName: "遮罩节点" })
    maskNode: cc.Node = null;
    @property(cc.Node)
    tipNode: cc.Node = null;

    /** 已经完成的游戏状态 */
    finishStateArr: Array<string> = [];
    /** 当前分数 */
    cur_score: number = 0;

    huaNode: cc.Node = null;   //画的节点
    isWin: boolean = false;

    start() {
        // cc.macro.ENABLE_MULTI_TOUCH = false;  //是否开起多点触摸
        EventManager.ins.on(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, this.finishTween, this);
        
    }
    onDestroy(): void {
        super.onDestroy();
        EventManager.ins.off(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, this.finishTween, this);
    }
    async init(huaPre: cc.Prefab) {
        if (this.interJson.sTitle) {
            this.sTitleLab.node.active = true;
            this.sTitleLab.string = this.interJson.sTitle + this.cur_score;
        }

        this.huaNode = cc.instantiate(huaPre);
        this.maskNode.addChild(this.huaNode);
        // 适配
        let widthScale = this.maskNode.width / this.huaNode.width;
        let heightScale = this.maskNode.height / this.huaNode.height;
        this.huaNode.scale = Math.min(widthScale, heightScale);

        this.huaNode.getComponent(TouchScale).maskNode = this.maskNode;
        if (cc.sys.os == cc.sys.OS_WINDOWS) {
            this.huaNode.on(cc.Node.EventType.MOUSE_WHEEL, (touches: cc.Event.EventMouse) => {
                this.huaNode.getComponent(TouchScale).mouseWheelCall(touches);
            }, this);
        }
        this.initHuaItem();
        this.initTouch();
    }


    finishTween(finishStr: any, lvItem: LvItem) {
        if (typeof finishStr != "string") {
            if (finishStr.str) {   //人物说话
                this.sayNodeTween(finishStr);
            }
            if (finishStr.sayInfo) {   //人物说话
                let isShow = false;
                if (finishStr.isShow) {
                    isShow = true;
                }
                this.sayNodeQipaoTween(finishStr.sayInfo, isShow);
            }
            return;
        }
        if (finishStr.includes("addState_")) {
            let str = finishStr.split("addState_")[1];
            this.addHaveStates([str]);
        }
        if (finishStr.includes("removeState_")) {
            let str = finishStr.split("removeState_")[1];
            this.removeStates([str]);
        }
        if (finishStr.includes("setClick_")) {  //设置一个lvItem_14的click
            let str = finishStr.split("setClick_")[1];
            this.setLvItemClick(lvItem.node, str == "true" ? true : false);
        }
        if (finishStr.includes("switchState")) {  //刷新是否胜利
            let item = lvItem.node.getComponent(LvItem_15);
            if (!item) { return console.error(lvItem.node.name + "没有挂载脚本LvItem_15"); }
            if (finishStr == "switchState") {
                item.switchState();
            } else {
                let str = finishStr.split("switchState_")[1];
                item.switchState(parseInt(str));
            }
        }

        if (finishStr == "stopTime") {
            EventManager.ins.emit(EVENT_NAME_ENUM.STOP_TIME);
        }
        if (finishStr.includes("pauseTime")) {
            EventManager.ins.emit(EVENT_NAME_ENUM.PAUSE_TIME);
        }

        if (finishStr == "overTalk") {
            this.overShowTalk(lvItem);
        }
        if (finishStr == "updateIsEnd") {  //判断是否全部步骤执行完  并执行胜利或者失败的Json 15-23炸鸡店打工用
            // 检测必要步骤是否做完
            for (let i = 0; i < this.interJson.mustStates.length; i++) {
                if (this.finishStateArr.indexOf(this.interJson.mustStates[i]) < 0) {
                    return;
                }
            }
            // 检测可选步骤有一个就完成
            for (let i = 0; i < this.interJson.optionalStates.length; i++) {
                if (this.finishStateArr.indexOf(this.interJson.optionalStates[i]) >= 0) {
                    this.updateIsWin();
                }
            }
        }
        if (finishStr == "updateIsWin") {  //判断是否胜利  并执行胜利或者失败的Json
            this.updateIsWin();
        }
        if (finishStr == "updateWin") {  //判断是否胜利  执行胜利Json
            if (this.getIsWin() && !this.isWin) {
                EventManager.ins.emit(EVENT_NAME_ENUM.STOP_TIME);
                UIManager.ins.enabledClick(false);
                this.runNodeTween(this.viewBg, this.getInterTwForName("winGameAni").interTween);
                this.isWin = true;
            }
        }
        if (finishStr.includes("addScore_")) {
            let score = finishStr.split("addScore_")[1];
            this.cur_score += Number(score);
            this.sTitleLab.string = this.interJson.sTitle + this.cur_score;
        }
        if (finishStr.includes("SzSTitle_")) {
            let Sz = finishStr.split("SzSTitle_")[1];      // 设置15关  二级标题 初始值！！！！例如：魅力值：---
            this.cur_score = Number(Sz);
            this.sTitleLab.string = this.interJson.sTitle + this.cur_score;
        }
        if (finishStr.includes("costStep")) {
            EventManager.ins.emit(EVENT_NAME_ENUM.ADD_STEP, -1, () => {
                UIManager.ins.enabledClick(false);
                this.runNodeTween(this.viewBg, this.getInterTwForName("overGameAni").interTween);
            });
        }
        if (finishStr.includes("TcStep")) {   // 广告弹窗  判断是否步数为0,打开广告弹窗
            EventManager.ins.emit(EVENT_NAME_ENUM.ADD_STEP, -1);
        }
    }

    isTouchMove: boolean = false;  //是否按住移动
    touchStartPos: cc.Vec3 = null;
    /** 初始化触摸 */
    initTouch() {
        // if (cc.sys.os == cc.sys.OS_WINDOWS) {
        //     this.huaNode.on(cc.Node.EventType.MOUSE_WHEEL, (touches: cc.Event.EventMouse) => {
        //         this.huaNode.getComponent(TouchScale).mouseWheelCall(touches);
        //     }, this);
        // }
        this.huaNode.on(cc.Node.EventType.TOUCH_START, (touches: cc.Event.EventTouch) => {
            this.isTouchMove = false;
            this.touchStartPos = cc.v3(touches.getLocation());


        }, this);
        this.huaNode.on(cc.Node.EventType.TOUCH_MOVE, (touchs: cc.Event.EventTouch) => {
            if (!this.touchStartPos || Tools.getDistance(this.touchStartPos, touchs.getLocation()) <= TOUCH_MOVE_LEN) { return; }
            this.isTouchMove = true;
            this.huaNode.getComponent(TouchScale).touchMoveCall(touchs);

        }, this);
        this.huaNode.on(cc.Node.EventType.TOUCH_END, (touchs: cc.Event.EventTouch) => {
            this.huaNode.getComponent(TouchScale).touchMoveEnd(touchs);
            this.isTouchMove = false;

        }, this);

    };
    /** 根据配置初始化 item */
    initHuaItem() {
        for (let i = 0; i < this.interJson.itemInfos.length; i++) {
            const info = this.interJson.itemInfos[i];
            let node = this.getChildForName(info.node)
            if (!node) { continue; }
            node.addComponent(LvItem_15).initItem(info, this);
            if (node.getComponent(LvItem)) { continue; }
            node.addComponent(LvItem).initItem(this);
        }
    };

    lastSayAudio: string = null;
    /** 执行说话事件 */
    async sayNodeTween(sayInfo: any) {
        let tempT = 3;
        if (sayInfo.audio) {
            AudioManager1.stopAudioForName(this.lastSayAudio);
            let audio = await AudioManager1.playAudio(sayInfo.audio.resUrl, sayInfo.audio.value, BUNDLE_TYPE_ENUM.LEVEL);
            this.lastSayAudio = sayInfo.audio.resUrl;
            tempT = cc.audioEngine.getDuration(audio) + 0.2;
        }

        if (sayInfo.armAni) {
            this.runArmAni(sayInfo.armAni, sayInfo.armAni.shuo, sayInfo.armAni.node);
        }

        if (sayInfo.str) {
            this.showTipNodeLab(sayInfo.str, tempT, sayInfo);
        }
        return tempT;
    };

    async sayNodeQipaoTween(sayInfo: any, isShow: boolean = false) {
        let sayNode = this.getChildForName(sayInfo.node);
        if (sayInfo.str && AudioManager1.isSubtitle) {
            sayNode.active = true;
            sayNode.getComponent(LvItem).setLabString(sayInfo.str);
        }

        if (sayInfo.armAni) {
            this.runArmAni(sayInfo.armAni, sayInfo.armAni.shuo, sayNode);
        }
        if (sayInfo.armAni2) {
            this.runArmAni(sayInfo.armAni2, sayInfo.armAni2.shuo, sayNode);
        }

        if (sayInfo.audio) {
            AudioManager1.stopAudioForName(this.lastSayAudio);
            let audio = await AudioManager1.playAudio(sayInfo.audio.resUrl, sayInfo.audio.value, BUNDLE_TYPE_ENUM.LEVEL);
            this.lastSayAudio = sayInfo.audio.resUrl;

            cc.Tween.stopAllByTarget(sayNode);
            let tempT = cc.audioEngine.getDuration(audio);
            cc.tween(sayNode)
                .delay(tempT)
                .call(() => {
                    if (!isShow) {
                        sayNode.active = false;
                    }
                    if (sayInfo.armAni) {
                        this.runArmAni(sayInfo.armAni, sayInfo.armAni.daiji, sayNode);
                    }
                    if (sayInfo.armAni2) {
                        this.runArmAni(sayInfo.armAni2, sayInfo.armAni.daiji, sayNode);
                    }
                }).start();
            return tempT;
        }
    };
    /** 通过sayInfo执行龙骨动画 */
    runArmAni(armAni: any, aniName: string, sayNode?: cc.Node) {
        if (!armAni) { return; }
        let node = sayNode.parent;
        if (armAni.node) {
            node = this.getNodeForName(armAni.node);
        }
        node.getComponent(LvItem).playArmtureAni(aniName);
    };
    /** 显示提示文字  time 显示时间 */
    showTipNodeLab(str: string, time: number, sayInfo: any) {
        cc.Tween.stopAllByTarget(this.tipNode);
        this.tipNode.active = AudioManager1.isSubtitle;

        let lab = this.tipNode.getComponentInChildren(cc.Label);
        if (str != "") {
            lab.string = str;
        }
        if (sayInfo.audio && sayInfo.audio.show) {
            cc.tween(this.tipNode)
                .to(0.5, { opacity: 255 })
                .delay(time)
                .call(() => {
                    if (sayInfo.armAni) {
                        this.runArmAni(sayInfo.armAni, sayInfo.armAni.daiji, sayInfo.armAni.node);
                    }
                    if (this.interJson["sayUpdateIsWin"]) {
                        this.updateIsWin();
                    }
                }).start();
        } else {
            cc.tween(this.tipNode)
                .to(0.5, { opacity: 255 })
                .delay(time)
                .call(() => {
                    if (sayInfo.armAni) {
                        this.runArmAni(sayInfo.armAni, sayInfo.armAni.daiji, sayInfo.armAni.node);
                    }
                    if (this.interJson["sayUpdateIsWin"]) {
                        this.updateIsWin();
                    }
                }).to(0.5, { opacity: 0 }).start();
        }

    };
    /** 是否过关 */
    getIsWin() {
        if (this.interJson.winStates.length != this.finishStateArr.length || this.finishStateArr.length <= 0) { return false; }
        for (let i = 0; i < this.finishStateArr.length; i++) {
            if (this.interJson.winStates.indexOf(this.finishStateArr[i]) < 0) {
                return false;
            }
        }
        return true;
    };

    /** 是否做过失败项 */
    getLose() {
        if (!this.interJson.loseStates || this.interJson.loseStates.length <= 0 || this.finishStateArr.length <= 0) { return false; }

        for (let i = 0; i < this.finishStateArr.length; i++) {
            if (this.interJson.loseStates.indexOf(this.finishStateArr[i]) >= 0) {
                return true;
            }
        }
        return false;
    };
    /** 是否做过插入项 */
    getCharu() {
        if (!this.interJson.charuStates || this.interJson.charuStates.length <= 0 || this.finishStateArr.length <= 0) { return false; }

        for (let i = 0; i < this.finishStateArr.length; i++) {
            if (this.interJson.charuStates.indexOf(this.finishStateArr[i]) >= 0) {
                return true;
            }
        }
        return false;
    };
    /** 设置本关Item的Click */
    setLvItemClick(node: cc.Node, isClick: boolean) {
        if (node.getComponent(LvItem_15)) {
            node.getComponent(LvItem_15).isClick = isClick;
        } else {
            cc.log("节点" + node.name + "上没有添加LvItem脚本");
        }
    };
    /** 结束说话 */
    async overShowTalk(lvItem: LvItem) {
        let info = this.getOverSayStr();
        lvItem.node.active = true;
        lvItem.node.scale = 0;
        let lab = lvItem.node.getComponentInChildren(cc.Label);
        lab.string = info.info;
        cc.tween(lvItem.node)
            .to(0.15, { scaleX: 1, scaleY: 1 }, { easing: cc.easing.backOut }).start();

        if (info.audio) {
            let audioId = await AudioManager1.playAudio(info.audio.resUrl, info.audio.value, BUNDLE_TYPE_ENUM.LEVEL);
            AudioManager1.setCallback(audioId, () => {
                UIManager.ins.enabledClick(false);
                if (this.getIsWin()) {
                    this.runNodeTween(this.viewBg, this.getInterTwForName("winGame").interTween);
                } else {
                    this.runNodeTween(this.viewBg, this.getInterTwForName("overGame").interTween);
                }
            })
        }
    };
    /** 刷新是否胜利 */
    updateIsWin() {
        UIManager.ins.enabledClick(false);
        // EventManager.ins.emit(EVENT_NAME_ENUM.STOP_TIME);
        EventManager.ins.emit(EVENT_NAME_ENUM.PAUSE_TIME);
        if (this.getIsWin()) {
            this.runNodeTween(this.viewBg, this.getInterTwForName("winGameAni").interTween);
        } else {
            this.runNodeTween(this.viewBg, this.getInterTwForName("overGameAni").interTween);
        }
    };
    /** 删除已经拥有的状态 */
    removeStates(states: Array<string>) {
        let removeArr = [];
        for (let i = 0; i < states.length; i++) {
            if (this.finishStateArr.indexOf(states[i]) >= 0) {
                Tools.removeArrForValue(this.finishStateArr, states[i]);
                removeArr.push(states[i]);
                i--;
            }
        }
        cc.log("删除状态数组:", this.finishStateArr);
        return removeArr; //返回所有删除成功的状态
    };
    /** 添加已经完成状态 */
    addHaveStates(states: Array<string>) {
        let addArr = [];
        for (let i = 0; i < states.length; i++) {
            if (this.finishStateArr.indexOf(states[i]) < 0) {
                this.finishStateArr.push(states[i]);
                addArr.push(states[i]);
            }
        }
        cc.log("添加状态数组:", this.finishStateArr);
        return addArr;   //返回所有添加成功的状态
    };
    /** 是否已经完成该有的状态 */
    isHaveStates(states?: Array<string>) {
        if (!states) { return true; }
        if (states.length > this.finishStateArr.length) {
            return false;
        }
        for (let i = 0; i < states.length; i++) {
            if (this.finishStateArr.indexOf(states[i]) < 0) {
                return false;
            }
        }
        return true;
    };
    /** 是否未完成该有的状态 */
    isHaveNoStates(state?: string | string[]) {
        cc.log("isHaveNoStates", state)
        if (!state) { return true; }
        if (typeof state === "string") {
            return this.finishStateArr.indexOf(state) < 0;
        } else {
            let count = 0;
            for (let i = 0; i < state.length; i++) {
                if (this.finishStateArr.indexOf(state[i]) < 0) {
                    count++;
                }
            }
            return count == state.length;
        }
    }
    /** 获取失败说的话 */
    getOverSayStr() {
        for (let i = 0; i < this.interJson.talkInfos.length; i++) {
            let states = this.interJson.talkInfos[i].state;
            let haveSates = this.interJson.talkInfos[i].haveSates;
            let isHave = false;
            if (states && !isHave) {
                for (let j = 0; j < states.length; j++) {
                    if (this.finishStateArr.indexOf(states[j]) >= 0) {
                        isHave = true;
                        break;
                    }
                }
            }
            if (haveSates && !isHave) {
                for (let j = 0; j < haveSates.length; j++) {
                    if (this.finishStateArr.indexOf(haveSates[j]) < 0) {
                        isHave = true;
                        break;
                    }
                }
            }
            if (!isHave) {
                return this.interJson.talkInfos[i];
            }
        }
        return this.interJson.talkInfos[0];
    };
}